package ar.edu.itba.pod.printer.impl;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

import ar.edu.itba.pod.printer.Document;
import ar.edu.itba.pod.printer.Printer;
import ar.edu.itba.pod.printer.PrinterDispatcher;

public class LimitedAsyncPrinterDispatcher implements PrinterDispatcher{

	private Printer printer = new Printer();
	private MyThread mythread;
	private BlockingQueue<Document> queue = 
		new LinkedBlockingQueue<Document>(5);
	
	
	public LimitedAsyncPrinterDispatcher() {
		mythread=new MyThread(){
			@Override
			public void excecute() {
				printIfNotEmpty();
			}
		};
		mythread.start();
	}
	
	@Override
	public void finishPrintRequests() {
		finishWorks();
		mythread.finish();
	}

	@Override
	public void printDocument(Document document) {
		try {
			queue.put(document);
//			System.out.print( "Q:"+queue.size() );
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			finishPrintRequests();
		}
	}
	
	public void finishWorks(){
		printIfNotEmpty();
	}
	
	public void printIfNotEmpty(){
		if(queue.size()>0){
			try {
				printer.print(queue.take());
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				System.out.println( "quice imprimir y algun otro me saco el trabajo" );
				e.printStackTrace();
			}
		}
		
	}

}
